﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Support.Design.Widget;
using Android.Support.V7.App;
using Android.Views;
using Android.Widget;

namespace Medicine.Activities
{
    [Activity(Label = "更新药品信息")]
    public class UpdateActivity : InsertActivity
    {
        private Models.Medicine _medicine;

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            //药品名称不可修改
            var medicineNameTxt = FindViewById<TextInputEditText>(Resource.Id.Txt_MedicineName);
            medicineNameTxt.Enabled = false;

            ConvertData();
            BindData();
        }

        /// <summary>
        /// 将父级页面传递过来的数据转换成需要的数据
        /// </summary>
        private void ConvertData()
        {
            var medicineJsonStr = this.Intent.GetStringExtra("medicine");
            if (string.IsNullOrEmpty(medicineJsonStr))
            {
                Helpers.MessageShow.ShowShortMsg(this, "传递数据错误！");
                return;
            }

            var tmpMedicine = Newtonsoft.Json.JsonConvert.DeserializeObject<Models.Medicine>(medicineJsonStr);
            if (tmpMedicine == null)
            {
                Helpers.MessageShow.ShowShortMsg(this, "转换数据错误！");
                return;
            }

            this._medicine = tmpMedicine;
        }

        /// <summary>
        /// 绑定数据
        /// </summary>
        private void BindData()
        {
            if (this._medicine != null)
            {
                var data = new Models.Medicine();
                var properties = data.GetType().GetProperties();
                var resource = typeof(Resource.Id);
                var resourceFields = resource.GetFields();

                foreach (var item in properties)
                {
                    var txtName = $"Txt_{item.Name}";
                    var txtResource = resourceFields.FirstOrDefault(s => s.Name == txtName);
                    if (txtResource == null)
                        continue;

                    var tmpObj = resource.Assembly.CreateInstance(txtResource.ReflectedType.Name);
                    var txtId = txtResource.GetValue(tmpObj);
                    if (txtId != null)
                    {
                        int tmpTxtId = Convert.ToInt32(txtId);
                        var itemVal = item.GetValue(this._medicine);
                        if (itemVal == null)
                            continue;

                        //时间或日期格式特殊处理
                        if (item.Name.Contains("Time") || item.Name.Contains("Date"))
                        {
                            EditText dateTxt = FindViewById<EditText>(tmpTxtId);
                            if (dateTxt != null)
                                dateTxt.Text = Convert.ToDateTime(itemVal).ToString("yyyy-MM-dd");
                            continue;
                        }

                        TextInputEditText txt = FindViewById<TextInputEditText>(tmpTxtId);
                        if (txt != null)
                            txt.Text = itemVal.ToString();
                    }
                }
            }
        }

        /// <summary>
        /// 重写保存事件
        /// </summary>
        protected override void SaveData()
        {
            var data = base.InitData();
            var msg = data.CheckData();
            if (msg.Result == Models.NoticeEnum.Failed)
            {
                Helpers.MessageShow.ShowNoticeMsg(this,
                                                    "保存失败提示",
                                                    msg.Message);
                return;
            }

            var hasData = DbContext.DbC.FirstQuery<Models.Medicine>(s => s.MedicineName == data.MedicineName);
            if (hasData != null && !string.IsNullOrEmpty(hasData.Id))
            {
                hasData.UpateData(data);
                var result = DbContext.DbC.Update(hasData);
                if (result > 0)
                {
                    Helpers.MessageShow.ShowShortMsg(this, "保存成功");
                    System.Threading.Tasks.Task.Delay(2000);
                    this.Finish();
                }
                else
                    Helpers.MessageShow.ShowShortMsg(this, "保存失败");
            }
            else
            {
                Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(this);
                builder.SetMessage($"药品名称{data.MedicineName}未记录是否继续添加？");
                builder.SetTitle("新数据增加提醒");

                builder.SetPositiveButton("确定", new EventHandler<DialogClickEventArgs>((s, e) =>
                {
                    base.SaveData();
                }));

                builder.SetNegativeButton("取消", new EventHandler<DialogClickEventArgs>((s, e) =>
                {

                }));

                builder.Create().Show();
            }
        }
    }
}